<template>
    <div class="tableList">
        <el-table
            :data="tableList" style="width: 100%;" border
            :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}" v-loading="loading" element-loading-text="加载中"
            element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading"
            :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}"
            ref='table'>
            <el-table-column
                v-for="(item, i) in tableGroup"
                :label="item.name"
                :prop="item.label"
                :min-width="item.width"
                :sortable="item.sortable"
                :fixed="item.fixed"
                show-overflow-tooltip
                :key='i'
            >
                <template slot-scope="scope">
                    <code v-show="item.label != 'workOrderState' && item.label != 'pricing' && item.label != 'verifyState'">
                        <code v-if='customImgSet(item.label, scope.row)'>
                            <p v-if='(JSON.parse(scope.row[item.label])).length <= 2'>
                                <img 
                                    :src="$global.uploadUrl + k.url" 
                                    alt="" 
                                    v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                    class="customImg"
                                    @click='costomImgPreview(i+1, (JSON.parse(scope.row[item.label])).length, JSON.parse(scope.row[item.label]))'
                                >
                            </p>
                            <p v-else>
                                <img
                                    :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[0].url" 
                                    alt="" 
                                    class="customImg" 
                                    @click='costomImgPreview(1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'
                                >
                                <span class='customImgMoreBox'>
                                    <div class='customImgMore'
                                        @click='costomImgPreview(2, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'
                                    >
                                        <el-popover
                                            placement="top"
                                            max-width="400"
                                            trigger="hover">
                                            <div class='customImgMore' slot="reference">+{{ JSON.parse(scope.row[item.label]).length - 2 }}</div>
                                            <img 
                                                :src="$global.uploadUrl + k.url" 
                                                alt="" 
                                                v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                                style="margin-right:10px"
                                                width='60px'
                                                height='60px'
                                                @click="costomImgPreview(i+1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))"
                                            >
                                        </el-popover>
                                    </div>
                                    <img 
                                        :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[1].url" 
                                        alt="" 
                                        class="customImg" 
                                    >
                                </span>
                            </p>
                        </code>
                        <code v-else>
                            <code v-if="customSelectSet(item.label, scope.row)">
                                <span
                                    v-for="(k, j) in customSelectList(item.label, scope.row)" :key="j"
                                    :style="customSelectStyle(item.label, scope.row, k)"
                                    class="customSelect"
                                >
                                    {{ k }}
                                </span>
                            </code>
                            <code v-else>
                                {{scope.row[item.label]}}
                            </code>
                        </code>
                    </code>
                    <code v-show="item.label == 'workOrderState'">
                        <span :style='workOrderStatus(scope.row[item.label])'></span>
                        {{ enumCon.worderOrderState(scope.row[item.label]) }}
                    </code>
                    <code v-show="item.label == 'pricing'">
                        {{ enumCon.pricingMethod(scope.row[item.label]) }}
                    </code>
                    <code v-show="item.label == 'verifyState'">
                        {{ enumCon.verifyStateState(scope.row[item.label]) }}
                    </code>
                </template>
                <el-table-column
                    v-for="(k, j) in item.children"
                    :label="k.name"
                    :prop="k.label + item.label"
                    :min-width="k.width"
                    :sortable="k.sortable"
                    show-overflow-tooltip
                    :key='j'
                >
                </el-table-column>
            </el-table-column>
            <div slot="empty">
                <el-empty :image-size="100"></el-empty>
            </div>
        </el-table>
        <el-pagination
            v-if="tableList.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10,20,50,100]"
            :page-size="formObj.limit"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total"
            background>
        </el-pagination>

        <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width='68%'>
            <el-carousel trigger="click" height="50vh" :autoplay='false' :initial-index='customImgData.initial' @change='handleCarousel' ref='carousel'>
                <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
                    <img :src="item.url" alt="" class='carouselImg'>
                </el-carousel-item>
            </el-carousel>
            <div class='imgDownLoad' @click='imgDownLoad'>
                <span class='el-icon-download'></span>
                下载
            </div>
        </el-dialog>
    </div>
</template>

<script>
import * as XLSX from "xlsx";
import request from '@/utils/request'
export default {
    props: {
        tableGroup: {
            type: Array,
            default: ''
        },
        tableList: {
            type: Array,
            default: ''
        },
        searchForm:{
            type:Object,
            default:() => ({})
        },
    },
    data() {
        return {
            loading: false,
            currentPage: 1, // 当前页数
            total: null, // 总条数
            formObj: this.searchForm,
            multipleSelection: [],
            customImgData: {
                visible: false,
                list: [],
                title: '',
                initial: 0,
                num: 0
            },
        }
    },
    mounted() {
        // this.total = this.tableList.length
    },
    methods: {
        getUrl(data, url) {
            return request({
                url: url,
                method: 'post',
                data,
            })
        },
        getTableData(name, url, searchForm, n) {
            if(this.multipleSelection.length == 0) {
                let data = {}
                for(let key in searchForm) {
                    if(searchForm[key] !== '' && searchForm[key] != undefined) {
                        data[key] = searchForm[key]
                    }
                }
                data.limit = this.total
                this.getUrl(data, url).then(res => {
                    if(res.code == 200) {
                        this.multipleSelection = res.data.records
                        this.multipleSelection.map((item, i) => {
                            item.index = (res.data.current - 1) * 10 + (i + 1)
                            if(n == '0') {
                                if(item.list) {
                                    item.list.map(k => {
                                        this.$set(item, k.time, k.num)
                                    })
                                }
                            } else {
                                if(item.customFieldVos != null) {
                                    item.customFieldVos.map(k => {
                                        item[k.customFieldId] = k.value,
                                        item.customType = k.customFieldMess.fieldType
                                    })
                                    let d = null
                                    this.tableGroup.map(k => {
                                        d = item.customFieldVos.find(r => { return r.customFieldId == k.label })
                                        if(d != undefined) {
                                            k.type = d.customFieldMess.fieldType
                                        }
                                    })
                                }
                            }
                        })
                        this.exportTable(name, true)
                    }
                })
            } else {
                this.exportTable(name)
            }
        },
        workOrderStatus(val) {
            var obj = {
                'display': 'inline-block',
                'margin-right': '10px',
                'width': '8px',
                'height': '8px',
                'border-radius': '50%'
            }
            if(val == '1') {
                obj.background = 'rgb(24, 145, 255)'
            }
            if(val == '2') {
                obj.background = 'rgb(2, 185, 128)'
            }
            if(val == '3') {
                obj.background = 'rgb(255, 59, 48)'
            }
            if(val == '0') {
                obj.background = 'rgb(232, 232, 232)'
            }
            return obj
        },
        // 分页
        handleSizeChange(val) {
            this.formObj.limit = val
            this.$emit('getTableData', this.formObj)
        },
        handleCurrentChange(val) {
            this.formObj.page = val
            let data = {}
            for(let key in this.formObj) {
                if(this.formObj[key]) {
                    data[key] = this.formObj[key]
                }
            }
            this.$emit('getTableData', data)
        },
        totalNum(n) {
            this.total = n
        },
        onloadLogin(state) {
            this.loading = state
        },
        
        // 导出
        exportTable(n, sta) {
            var that = this;
            let dataArr = this.tableGroup.filter(item => item.type != 'picture' && item.type != 'upload')
            import("@/excel/export2Excel").then((excel) => {
                const { export_json_to_excel } = require('@/excel/export2Excel'); // 这里必须使用绝对路径，使用@/+存放export2Excel的路径
                let tHeader = dataArr.map(item => { return item.name }); // 导出的表头名信息
                let filterVal = dataArr.map(item => { return item.label }); // 导出的表头字段名，需要导出表格字段名
                let headerStyle = []
                const list = that.multipleSelection;
                let check = dataArr.find(res => { return res.type == 'selectChecked' })
                if(check != undefined) {
                    list.map((item,i) => {
                        if(item[check.label]) {
                            try {
                                item[check.label] = JSON.parse(item[check.label]).join(',')
                            } catch {
                                
                            }
                        }
                    })
                }
                list.map(item => {
                    if(item.vos) {
                        let d = item.vos;
                        let str = []
                        d.map(j => {
                            str.push(j.name)
                        })
                        item.vos = str.join(',')
                    }
                })
                const data = that.formatJson(filterVal, list);
                var sheet = XLSX.utils.json_to_sheet(data, {
                    skipHeader: true,
                });
                for (const key in sheet) {
                    // 第一行，表头
                    if (key.replace(/[^0-9]/ig, '') === '1') {
                        headerStyle.push(key)
                    }
                }
                excel.export_json_to_excel2({
                    header: tHeader,
                    data,
                    filename: n,
                    headerStyle
                });// 导出的表格名称，根据需要自己命名

                if(sta) {
                    this.multipleSelection = []
                }
            });
        },
        formatJson (filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },

        // 自定义=====================================
        // 自定义字段 复选框/单选框 列
        customSelectSet(t, d) {
            let state = false
            if(d.customFieldVos != null) {
                d.customFieldVos.map(item => {
                    if(item.customFieldMess != null) {
                        if((item.customFieldMess.fieldType == 'selectRadio' || item.customFieldMess.fieldType == 'selectChecked') && t == item.customFieldId) {
                            state = true
                        }
                    }
                })
                return state
            } else {
                return false
            }
        },
        customSelectList(t, d) {
            if(d[t] == '' || d[t] =='[]') {
                return []
            } else {
                let data = []
                try {
                    data =  JSON.parse(d[t])
                } catch {
                    data = d[t].split(',')
                    data[0] == '' ? data = [] : ''
                }
                data === Number(data) ? data = [data] : ''
                return data
            }
        },
        customSelectStyle(t, d, v) {
            let style = {}
            if(d.customFieldVos != null) {
                let obj = d.customFieldVos.find(res => { return res.customFieldId == t })
                if(obj.value != '' && obj.value != '[]' && obj.value != null) {
                    if(obj.customFieldMess.fieldType == 'selectRadio') {
                        let color = JSON.parse(obj.customFieldMess.checkBox).find(res => { return obj.value == res.value })
                        if(color != undefined) {
                            return {
                                color: color.color,
                                background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color.length - 4) + ', .1)'
                            }
                        } else {
                            return {
                                color: '#333',
                                background: '#f4f4f5'
                            }
                        }
                    }
                    if(obj.customFieldMess.fieldType == 'selectChecked') {
                        let color = JSON.parse(obj.customFieldMess.checkBox).find(res => { return v == res.value })
                        if(color != undefined) {
                            return {
                                color: color.color,
                                background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color.length - 4) + ', .1)'
                            }
                        } else {
                            return {
                                color: '#333',
                                background: '#f4f4f5'
                            }
                        }
                    }
                }
            }
        },
        // 自定义字段图片列
        customImgSet(t, d) {
            let state = false
            if(d.customFieldVos != null) {
                d.customFieldVos.map(item => {
                    if(item.customFieldMess != null) {
                        if(item.customFieldMess.fieldType == 'picture' && t == item.customFieldId) {
                            state = true
                        }
                    }
                })
                return state
            } else {
                return false
            }
        },
        // 自定义图片预览
        costomImgPreview(i, len, list) {
            this.customImgData.visible = true
            this.customImgData.title = '预览' + ' (' + i + '/' + len + ')'
            this.customImgData.initial = Number(i) - 1
            this.customImgData.list = list.map(item => {
                return {
                    name: item.name,
                    url: this.$global.uploadUrl + item.url
                }
            })
            this.customImgData.num = i - 1
            this.setActiveItem(i - 1)
        },
        setActiveItem(i) {
            if (this.$refs.carousel) {
                this.$refs.carousel.setActiveItem(i)
            }
        },
        // 图片预览轮播切换
        handleCarousel(v) {
            this.customImgData.title = '预览' + ' (' + (Number(v) + 1) + '/' + this.customImgData.list.length + ')'
            this.customImgData.num = v
        },
        // 图片下载
        imgDownLoad() {
            window.open(this.customImgData.list[this.customImgData.num].url, "_blank");
        },
        changeLayout() {
            this.$nextTick(() => {
                this.$refs.table.doLayout()
            })
        }
    },
    watch: {
        // 表格数据
        tableList: function(newVal, oldVal) {
        },
        searchForm: {
            handler(val) {
                this.formObj = val
            },
            deep: true
        }
    },
    beforeUpdate() {
        this.$nextTick(() => {
            this.$refs.table.doLayout()
        })
    }
}
</script>

<style lang="less" scoped>
    .tableList {
        padding: 0 20px;

        code{
            font-family: sans-serif;
        }
        .customImg {
            width: 60px;
            height: 60px;
            margin-right: 10px;
            cursor: pointer;
        }
        .customImgMoreBox {
            position: relative;
            height: 100%;
            display: inline-block;
            .customImgMore {
                position: absolute;
                left: 0;
                top: 0;
                width: 60px;
                height: 60px;
                background: rgba(0,0,0,.3);
                color: #fff;
                font-size: 10px;
                line-height: 60px;
                text-align: center;
                cursor: pointer;
            }
        }

        .progress {
            display: flex;

            .item_progress {

                .progress_circle {
                    display: flex;
                    align-items: center;

                    .line {
                        width: 30px;
                        height: 2px;
                        background-color: rgb(24, 144, 255);
                        margin: 0px 3px;
                    }
                }

                span {
                    color: #5a5a5a;
                    font-size: 12px;
                    display: inline-block;
                    width: 38px;
                    text-align: center;
                }

                /deep/ .el-progress-circle {
                    width: 38px !important;
                    height: 38px !important;
                }

                /deep/ .el-progress__text {
                    font-size: 12px !important;
                }
            }
        }

        .circle {
            display: inline-block;
            background: rgb(24, 145, 255);
            margin-right: 10px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }
    }

    /deep/ .el-table th>.cell {
        line-height: 34px;
    }

    /deep/ .el-table .caret-wrapper {
        float: right;
    }
    /deep/ .el-table th.gutter{
        display: table-cell!important;
    }
    /deep/ .el-table__cell {
        text-align: center;
    }
    /deep/ .is-leaf {
        text-align: left;
    }
    /deep/ .el-table__row {
        .el-table__cell {
            text-align: left;
        }
    }
</style>